from django.db import models
import uuid


class FontCategory(models.Model):
    """字体分类表"""
    objects = models.Manager()

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, max_length=255, verbose_name="分类ID")
    name = models.CharField(max_length=50, verbose_name="分类名称")
    code = models.CharField(max_length=50, unique=True, verbose_name="分类编码")
    description = models.TextField(null=True, blank=True, verbose_name="分类描述")
    sort_order = models.IntegerField(default=0, verbose_name="排序")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "font_categories"
        verbose_name = "字体分类"
        verbose_name_plural = "字体分类"
        ordering = ['sort_order']

    def save(self, *args, **kwargs):
        if not self.sort_order:
            # 获取当前最大排序值
            max_order = FontCategory.objects.aggregate(
                models.Max('sort_order'))['sort_order__max']
            self.sort_order = (max_order or 0) + 1
        super().save(*args, **kwargs)


def font_file_path(instance, filename):
    """生成字体文件存储路径"""
    ext = filename.split('.')[-1]
    return f'fonts/{ext.lower()}/{instance.family}/{filename}'


def preview_image_path(instance, filename):
    """生成预览图存储路径"""
    return f'fonts/svg/{instance.family}/{filename}'


class Font(models.Model):
    """字体表"""
    objects = models.Manager()

    FORMAT_CHOICES = [
        ("TTF", "TrueType"),
        ("OTF", "OpenType"),
        ("WOFF", "Web Open Font Format"),
        ("WOFF2", "Web Open Font Format 2")
    ]

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, max_length=255, verbose_name="字体ID")
    category = models.ForeignKey(FontCategory, on_delete=models.SET_NULL, null=True, related_name="fonts",
                                 verbose_name="字体分类")
    name = models.CharField(max_length=100, verbose_name="字体名称")
    family = models.CharField(max_length=100, verbose_name="字体族名")
    file_url = models.FileField(upload_to=font_file_path, null=True, blank=True, verbose_name="字体文件")
    file_format = models.CharField(max_length=10, choices=FORMAT_CHOICES, verbose_name="文件格式")
    preview_image = models.FileField(upload_to=preview_image_path, null=True, blank=True, verbose_name="预览图svg")
    is_favorite = models.BooleanField(default=False, verbose_name="是否收藏")
    is_system = models.BooleanField(default=False, verbose_name="是否系统字体")
    font_weight = models.CharField(max_length=50, default="400", verbose_name="字重")
    font_style = models.CharField(max_length=50, default="normal", verbose_name="字体样式")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "fonts"
        verbose_name = "字体"
        verbose_name_plural = "字体"

    def delete(self, *args, **kwargs):
        # 删除字体文件
        if self.file_url:
            storage = self.file_url.storage
            if storage.exists(self.file_url.name):
                storage.delete(self.file_url.name)

        # 删除预览图文件
        if self.preview_image:
            storage = self.preview_image.storage
            if storage.exists(self.preview_image.name):
                storage.delete(self.preview_image.name)

        # 调用父类的delete方法删除数据库记录
        super().delete(*args, **kwargs)